// DlgSettingUser.cpp : implementation file
//

#include "stdafx.h"
#include "XIE.h"
#include "DlgSettingUser.h"
#include "MainFrm.h"
#include <ExDispid.h>

// CDlgSettingUser dialog

IMPLEMENT_DYNCREATE(CDlgSettingUser, CDHtmlDialog)

CDlgSettingUser::CDlgSettingUser(CWnd* pParent /*=NULL*/)
	: CDHtmlDialog(CDlgSettingUser::IDD, NULL, pParent)
{
	m_bAutoClose = FALSE;
}

CDlgSettingUser::~CDlgSettingUser()
{
}

void CDlgSettingUser::DoDataExchange(CDataExchange* pDX)
{
	CDHtmlDialog::DoDataExchange(pDX);
}

BOOL CDlgSettingUser::OnInitDialog()
{
	CDHtmlDialog::OnInitDialog();
	CString strURL;		

	DWORD dwOEMID = AfxGetApp()->GetProfileInt(_T("OEM"), _T("ID"), 0);
	strURL.Format(IDS_USER_URL, dwOEMID);
	//CURLEncode url;
	//CString strURL1 = url.URLEncode((LPCTSTR)strURL);
	if (!strURL.IsEmpty())
	{
		Navigate(strURL);
		//Navigate(_T("file:///d:/index.html"));
	}
	return TRUE;  // return TRUE  unless you set the focus to a control
}

BEGIN_MESSAGE_MAP(CDlgSettingUser, CDHtmlDialog)
END_MESSAGE_MAP()

BEGIN_DHTML_EVENT_MAP(CDlgSettingUser)
	DHTML_EVENT_ONCLICK(_T("ButtonOK"), OnButtonOK)
	DHTML_EVENT_ONCLICK(_T("ButtonCancel"), OnButtonCancel)
END_DHTML_EVENT_MAP()


BEGIN_EVENTSINK_MAP(CDlgSettingUser, CDHtmlDialog)
	ON_EVENT(CDlgSettingUser, AFX_IDC_BROWSER, DISPID_NEWWINDOW2, OnNewWindow2, VTS_PDISPATCH VTS_PBOOL)
END_EVENTSINK_MAP()

// CDlgSettingUser message handlers

HRESULT CDlgSettingUser::OnButtonOK(IHTMLElement* /*pElement*/)
{
	CDHtmlDialog::OnOK();
	return S_OK;
}

HRESULT CDlgSettingUser::OnButtonCancel(IHTMLElement* /*pElement*/)
{
	CDHtmlDialog::OnCancel();
	return S_OK;
}

void CDlgSettingUser::OnDocumentComplete(LPDISPATCH pDisp, LPCTSTR szUrl)
{
	CDHtmlDialog::OnDocumentComplete(pDisp, szUrl);

	
	CString strDocURL;
	GetCurrentUrl(strDocURL);
	if (strDocURL.IsEmpty() || strDocURL != szUrl)
		return;

	IHTMLDocument2* pDocument = NULL;	

	HRESULT hr = GetDHtmlDocument(&pDocument);

	if(FAILED(hr) || !pDocument)
		return;

	GetUserInfoFromHtmlDocment(pDocument);
	
	if (!theApp.m_strUserID.IsEmpty())
	{
		//AfxGetApp()->WriteProfileString(_T("user"), _T("id"), theApp.m_strUserID);
		//AfxGetApp()->WriteProfileString(_T("user"), _T("name"), theApp.m_strUserName);
		//AfxGetApp()->WriteProfileString(_T("user"), _T("pw"), theApp.m_strPassword);
		if (m_bAutoClose)
			CDialog::OnOK();
	}

	// TODO: Add your specialized code here and/or call the base class
}

void CDlgSettingUser::OnNewWindow2(LPDISPATCH* ppDisp, BOOL* Cancel)
{
	//*Cancel = FALSE;
	CMainFrame* pWndMainfram = (CMainFrame*)AfxGetMainWnd();

	if (pWndMainfram)
	{
		CXIEView* pIE = pWndMainfram->NewIEView(FALSE);
		if (pIE)
		{
			pIE->SetRegisterAsBrowser(TRUE);   
			*ppDisp = pIE->GetApplication();	
		}
	}
}